#!/bin/bash
trap 'echo Abort ; exit 1' ERR

if(test -L $0) then
    	auxlink=`ls -l $0 | sed 's/^[^>]*-> //g'`
    	M_HOME=`dirname $auxlink`/
else 
    	M_HOME=`dirname $0`/
fi
cd $M_HOME

PACKAGE_DIR=$PWD/package
export SOURCE_DIR=$PWD/source
ROOTFS_DIR=/opt/armgcc/rootfs
MODULE_DIR=/opt/armgcc/kernelmodule
TARGET=arm-linux-gnueabi

[ -d $PACKAGE_DIR -a -d $SOURCE_DIR -a -d $ROOTFS_DIR -a -d $MODULE_DIR ] || {
	echo 'one of the following does not exist: '
	echo $PACKAGE_DIR ; echo $SOURCE_DIR ; echo $ROOTFS_DIR ; echo $MODULE_DIR ; exit 1
}

if [ $1 -a $1 == clean ] ; then 
	echo Clean Linux Kernel.
	rm $SOURCE_DIR/linux* -rf
	exit 0
fi

echo Build Linux Kernel.

[ -f pkglist -o -f patchlist -o -f varlist ] && {
	echo '`pkglist`,`patchlist` or `varlist` exist, I won''t overwrite them. Abort.'
	exit 1
}

$PACKAGE_DIR/download pkglist
cp *.patch /srcpkg/
ls -1 *.patch > patchlist
$SOURCE_DIR/unpackAndPatch pkglist patchlist
./dirvar pkglist > varlist
rm pkglist patchlist -f
. varlist
rm varlist -f

err() { echo "Error. $@ not set."; exit 1; }
[ -z "$LINUX" ] && err LINUX

cd $SOURCE_DIR/$LINUX
ARG="ARCH=arm CROSS_COMPILE=${TARGET}- INSTALL_MOD_PATH=$MODULE_DIR"
set -x
make mrproper > /dev/null
make $ARG at91sam9263ek_defconfig > /dev/null
./modifyconfig
make $ARG > /dev/null
make $ARG modules_install > /dev/null
set +x
/opt/armgcc/deploy/mkimage -A arm -O linux -T kernel -C none -a 0x20008000 -e 0x20008000 -n $LINUX -d arch/arm/boot/zImage ../../uImage.bin

cd -
cp uImage.bin /opt/armgcc/deploy/
